package utils.data 
{
	import flash.net.registerClassAlias;
	import flash.net.SharedObject;
	import flash.sampler.getSize;
	import flash.utils.ByteArray;
	import flash.utils.Dictionary;
	import vo.CastleVO;
	import vo.GeneralVO;
	import vo.PlayerVO;
	import vo.SystemVO;
	/**
	 * ...
	 * @author WLDragon 2014-02-23
	 */
	public class DB 
	{
		
		public function DB() 
		{
			registerClassAlias("vo.CastleVO", CastleVO);
			registerClassAlias("vo.GeneralVO", GeneralVO);
			registerClassAlias("vo.PlayerVO", PlayerVO);
			registerClassAlias("vo.SystemVO", SystemVO);
			
			vos = new Dictionary();
			xmls = new Dictionary();
			maps_b = new Dictionary();
			maps_d = new Dictionary();
		}
		
		/**
		 * 解析数据
		 * @param	data 数据
		 * @param	type 类型 Cnt.DB_*
		 */
		public function parseData(data:ByteArray,type:int):void
		{
			switch (type) 
			{
				case Cnt.DB_TYPE_VO:
					vos = (new ParseVOData()).parseData(data);
				break;
				case Cnt.DB_TYPE_XML:
					xmls = (new ParseXmlData()).parseData(data);
				break;
				case Cnt.DB_TYPE_MAPB:
					maps_b = (new ParseMapData()).parseData(data);
				break;
				case Cnt.DB_TYPE_MAPD:
					maps_d = (new ParseMapData()).parseData(data);
				break;
			}
		}
		
		/**
		 * 获取数据记录,即VO类实例
		 * @param	key 类名 Cnt.VO_*
		 * @param	id  记录标识
		 * @return  VO类实例
		 */
		public function getRecord(key:String,id:int):*
		{
			return vos[key][id];
		}
		
		/**
		 * 获取数据集,即同一类型的VO类实例集合
		 * @param	key 类名 Cnt.VO_*
		 * @return
		 */
		public function getTable(key:String):Dictionary
		{
			return vos[key] as Dictionary;
		}
		
		/**
		 * 获取XML配置文件
		 * @param	key 文件名 Cnt.XML_*
		 * @return
		 */
		public function getXml(key:String):XML
		{
			return xmls[key] as XML;
		}
		
		/**
		 * 销毁XML
		 * @param	key 文件名 Cnt.XML_*
		 */
		public function destroyXml(key:String):void
		{
			delete xmls[key];
		}
		
		/**
		 * 获取地图的构建文件
		 * @param	castleId 城池ID 
		 * @return
		 */
		public function getMapData_B(castleId:int):ByteArray
		{
			return maps_b["map_" + castleId] as ByteArray;
		}
		
		public function getMapData_D(castleId:int):ByteArray
		{
			return maps_d["map_" + castleId] as ByteArray;
		}
		
		/**
		 * 保存进度
		 */
		public function save():void
		{
			var o:SharedObject = SharedObject.getLocal("Sangokushi2-flash-2014");
			var b:ByteArray = new ByteArray();
			b.writeObject(vos);
			b.compress();
			o.data.store = b;
			o.flush();
		}
		
		/**
		 * 读取进度
		 */
		public function load():Boolean
		{
			var o:SharedObject = SharedObject.getLocal("Sangokushi2-flash-2014");
			if (o.data.store)
			{
				var b:ByteArray = new ByteArray();
				b.writeBytes(o.data.store);
				b.uncompress();
				vos = b.readObject() as Dictionary;
				return true;
			}
			return false;
		}
		
		private var vos:Dictionary;
		private var xmls:Dictionary;
		private var maps_d:Dictionary;
		private var maps_b:Dictionary;
	}

}